﻿using System;

namespace InDepth2Demo.Chapter8
{
    /// <summary>
    /// 8.5 匿名类型
    /// </summary>
    public class AnonymousType
    {
        public static void Call()
        {
            var tom = new { Name = "Tom", Age = 6 };

            Console.WriteLine($"{tom.Name} - {tom.Age}");

            var family = new[]
            {
                new { Name = "Holly", Age = 36 },
                new { Name = "Jon", Age = 36 },
                new { Name = "Tom", Age = 9 },
                new { Name = "Robin", Age = 6 },
                new { Name = "William", Age = 6 }
            };
            //family[0].Name = "123";       //只读的，不能赋值

            // 如果其中的匿名对象 不是包含相同的数量的属性，或者以相同顺序出现，那么编译器就会报错
            //            var family2 = new[]
            //{
            //    new { Name = "Holly", Age = 36 },
            //    new { Name = "Jon", Age = 36 },
            //    new { Name = "Tom", Age = 9 },
            //    new { Name = "Robin", Age = 6 },
            //    new { Age = 6,Name = "William" }
            //};

            int totalAge = 0;
            foreach (var person in family)
            {
                totalAge += person.Age;
            }
            Console.WriteLine("Total age: {0}", totalAge);

            // 3. 隐式类型数组出错的情况
            // var errorarray = new[] { "hello", 3 };
        }

        public static void IsEquals()
        {
            var tom = new { Name = "Tom", Age = 6 };
            var tom2 = new { Name = "Tom", Age = 6 };               // 要是属性调换顺序 Equals就为false
            Console.WriteLine($"tom=tom2: {tom.Equals(tom2)}");  // True
            Console.WriteLine($"{tom.GetHashCode()}, {tom2.GetHashCode()}");       // -2084341341, -2084341341

            Person p1 = new Person { Name = "Tom", Age = 6 };
            Person p2 = new Person { Name = "Tom", Age = 6 };
            Console.WriteLine($"p1=p2: {p1.Equals(p2)}");  // False
            Console.WriteLine($"{p1.GetHashCode()}, {p2.GetHashCode()}");      // 46104728, 12289376
        }
    }
}
